<template>
  <div class="container-box">
    <div class="table-wrap">
      <div class="filter-box">
        <el-form :inline="true" :model="query" class="demo-form-inline">
          <template v-for="(item, index) in columns.filter(d => d.isFilter)">
            <el-form-item :key="index" :label="item.title">
              <el-input v-model="query[item.key]" :placeholder="`请输入${item.title}`" />
            </el-form-item>
          </template>
        </el-form>
        <el-row class="button-row">
          <el-button type="primary" icon="el-icon-plus" @click="handleTableOp('add')">新增客户</el-button>
          <el-button type="primary" icon="el-icon-search" @click="getData">查询</el-button>
        </el-row>
      </div>
      <div class="table-box">
        <el-table :data="list" border stripe header-row-class-name="table-header-row">
          <template v-for="(column, index) in columns.filter(d => d.isTable)">
            <el-table-column :key="index" :prop="column.key" :label="column.title">
              <template slot-scope="scope">
                <div v-if="column.key === ''" class="">{{ scope.row[column.key] }}</div>
                <div v-else-if="column.key === 'company_name'">
                  <el-tooltip class="item" effect="dark" :content="getCustomerRecord(scope.row)" placement="right">
                    <span><i class="el-icon-info" />{{ handleRowResult(column, scope.row) }}</span>
                  </el-tooltip>
                </div>
                <div v-else class="">{{ handleRowResult(column, scope.row) }}</div>
              </template>
            </el-table-column>
          </template>
        </el-table>
      </div>
      <el-pagination :current-page="paging.page" :page-sizes="pageSizes" :page-size="paging.limit" layout="total, sizes, prev, pager, next, jumper" :total="paging.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <v-customer-add-com ref="addCom" @callback="handleAddComCb" />
  </div>
</template>

<script>
import { storeIndex, storeHouse, storeAdd, addStoreHouse } from '../../api/store';

import curde from '@/mixins/curde'
import CustomerAddCom from './add.vue'
export default {
  components: { vCustomerAddCom: CustomerAddCom },
  mixins: [curde],
  data() {
    return {
      storeId: '',
      columns: [
        { title: '门店', key: 'store_id', type: 'text', isFilter: false, isTable: false, isForm: true },
        { title: '单位名称', key: 'company_name', type: 'text', isFilter: false, isTable: true, isForm: true },
        { title: '单位名称—简称', key: 'full_company_name', type: 'text', isFilter: false, isTable: false, isForm: true },
        { title: '联系人', key: 'customer_name', type: 'text', isFilter: false, isTable: true, isForm: true },
        { title: '移动电话', key: 'phone', type: 'text', isFilter: false, isTable: true, isForm: true },
        { title: '固定电话', key: 'tel_phone', type: 'text', isFilter: false, isTable: false, isForm: true },
        { title: '区域', key: 'area', type: 'text', isFilter: false, isTable: true, isForm: true },
        { title: '详细地址', key: 'area_address', type: 'text', isFilter: false, isTable: false, isForm: true },
        { title: '企业类型', key: 'company_type', type: 'text', isFilter: false, isTable: true, isForm: true },
        { title: '供销类型', key: 'customer_type', type: 'text', isFilter: false, isTable: false, isForm: true },
        { title: '开户行', key: 'bank_name', type: 'text', isFilter: false, isTable: false, isForm: true },
        { title: '银行帐号', key: 'bank', type: 'text', isFilter: false, isTable: false, isForm: true },
        { title: '状态', key: 'status', type: 'text', isFilter: false, isTable: false, isForm: true },
        { title: '备注', key: 'remarks', type: 'text', isFilter: false, isTable: false, isForm: true }
      ],
      allList: [],
      list: [],
      query: {},
      storeDialogVisible: false,
      storeForm: {
        store_no: '003',
        store_name: '测试门店',
        area: '测试门店地址',
        area_address: '测试门店详细地址'
      },
      storeRules: {
        // store_house_name: [{ required: true, message: '请输入仓库名称', trigger: ['change', 'blur'] }],
        // store_id: [{ required: true, message: '请选择所属门店', trigger:  ['change', 'blur'] }],
        // area_address: [{ required: true, message: '请输入地址', trigger:  ['change', 'blur'] }]
      },

      storeHouseColums: [
        { title: '仓库名称', key: 'store_house_name', type: 'text', isFilter: false, isTable: true, isForm: true },
        { title: '所属门店', key: 'store_id', type: 'text', isFilter: false, isTable: true, isForm: true },
        { title: '地址', key: 'area_address', type: 'text', isFilter: false, isTable: true, isForm: true }
      ],
      // storeHouseList: [],
      storeHouseQuery: {},
      storeHouseDialogVisible: false,
      storeHouseForm: {
        // store_house_name: '',
        // store_id: '',
        // area_address: '',
      },
      storeHouseRules: {
        store_house_name: [{ required: true, message: '请输入仓库名称', trigger: ['change', 'blur'] }],
        store_id: [{ required: true, message: '请选择所属门店', trigger: ['change', 'blur'] }],
        area_address: [{ required: true, message: '请输入地址', trigger: ['change', 'blur'] }]
      },
      dict: {}
    };
  },
  computed: {
    // 客户类型字典；
    companyTypeDict() {
      const company_type = this.dictDetails?.company_type || [];
      const companyTypeDict = {};
      if (company_type.length) {
        company_type.forEach(d => {
          companyTypeDict[d.value] = d.label;
        })
      }
      return companyTypeDict;
    }
  },
  watch: {
    storeHouseDialogVisible(val, oldVal) {
      this.storeHouseForm = {}
    }
  },
  created() {
    console.log('system==', this.system);
    this.getData();
  },
  methods: {
    // 客户商品记录
    getCustomerRecord(row) {
      if (row && row?.config) {
        const config = JSON.parse(row.config);
        const goods_record = config?.goods_record;
        if (goods_record && Object.keys(goods_record).length) {
          console.log('getCustomerRecord--goods_record==', goods_record);
          const goods_record_str = Object.keys(goods_record).map(d => {
            console.log('d==', d);
            if (goods_record[d].length) {
              const goodsItem = goods_record[d].map(g => {
                const goodsItemStr = `${g.goods_name} ${g.goods_sku} ${g.goods_price}元 ${this.$moment(g.update_time).format('YYYY-MM-DD')}`
                return goodsItemStr;
              })
              return goodsItem.join(', \n')
            }
            else {
              return '';
            }
          })
          return goods_record_str.join(', \n');
        }
        else {
          return '';
        }
      }
      else {
        return '';
      }
    },
    // 新增组件返回；
    handleAddComCb(isFlag, result) {
      console.log('handleAddComCb--', isFlag, result);
      if (isFlag) {
        this.getData();
      }
    },
    // 操作按钮
    handleTableOp(type, row) {
      if (type === 'add') {
        this.$refs.addCom.showDialog('add');
      }
      else if (type === 'edit') {
        this.$refs.addCom.showDialog('edit', { id: row.id });
      }
    },
    async onSubmit(type) {
      console.log('onSubmit==', type);
      if (!type) return;

      let isValid = false; let msg = '';
      this.$refs[type].validate(valid => {
        isValid = valid;
      })
      if (this.saving) msg = '请勿重复提交';
      if (!isValid) msg = '请检查提交内容';
      if (msg) {
        this.$message.error(msg)
        return;
      }
      this.saving = true;
      if (type === 'storeForm') {
        console.log('storeForm==', this.storeForm);
        const payload = this.$json.cloneDeep(this.storeForm)
        const { data } = await storeAdd(payload);
        console.log('addStoreHouse==', data);
        if (data && data.length === 2) {
          if (data[1]) {
            this.$store.dispatch('store/getStoreList')
            this.$store.dispatch('store/getStoreHouseList')
            this.$message.success('添加成功')
            this.storeDialogVisible = false;
          } else {
            this.$message.error(`添加失败: ${payload.store_no} || ${payload.store_name} 已存在`)
          }
        } else {
          this.$message.error(`异常：添加失败`)
        }
      }
      else if (type === 'storeHouseForm') {
        const res = await addStoreHouse(this.storeHouseForm);
        console.log('addStoreHouse==', res);
        await this.$store.dispatch('store/getStoreHouseList');
        this.storeHouseDialogVisible = false;
      }
      this.saving = false;
    },
    async getData() {
      const list = await this.$store.dispatch('customer/getCustomerList')
      console.log('customer--getData--list==', list);
      this.allList = list || [];
      this.handleList()
    },
    // 展示符合条件的数据
    handleList() {
      this.list = this.filterData(this.allList, this.createPayload(this.query))
      this.paging.total = this.list.length;
    },

    handleRowResult(item, row) {
      // console.log('handleRowResult--item', item, row);
      if (item.key === 'stock') {
        if (row.stock && row.unit_name2 && row.unit_convert !== row.unit_convert2) {
          const unitNum = row.stock % row.unit_convert2;
          const unitNum2 = Math.floor(row.stock / row.unit_convert2);
          return `${unitNum2}${row.unit_name2}${unitNum}${row.unit_name}`
        }
        return `${row.stock}${row.unit_name}`
      }
      if (item.key === 'store_id') {
        return this.dict.store[row[item.key]]?.store_name || row[item.key];
      }
      if (item.key === 'phone' || item.key === 'tel_phone') {
        return row[item.key] || row?.phone || row?.tel_phone || ''
      }
      if (item.key === 'company_type') {
        return this.companyTypeDict[row[item.key]] || row[item.key];
      }
      return row[item.key] || '';
    }
  }
}

</script>
<style lang="scss" scoped>
.container-box {
  padding: 20px;
  .table-wrap {
    margin-top: 40px;
    .filter-box {
      margin-bottom: 10px;
    }
    ::v-deep .table-header-row {
      color: #000;
      font-weight: bold !important;
    }
  }
}
::v-deep .el-tooltip__popper {
  white-space: pre !important;
}
</style>
